package com.ykdl.member.kid.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.view.Display;

import com.ykdl.member.KidApp;
import com.ykdl.member.base.QLog;
/**
 * 
 * 得到图像缩略图
 * @see
 * @since 1.0
 */

public class MThumbnailPhoto {
	private static MThumbnailPhoto mListPhoto = new MThumbnailPhoto();
	private static Context mContext;
	
	private MThumbnailPhoto() {
		super();
		// TODO Auto-generated constructor stub
	}

	public static synchronized MThumbnailPhoto getInstance(Context context) {
		MThumbnailPhoto.mContext = context;
		return mListPhoto;
	}

	public Bitmap getThumbnail(String urlPath) {
		Bitmap bitmap = BitmapFactory.decodeFile(urlPath);
		return bitmap;

		/*
		 * byte[] imageByte = null; try { imageByte = getImageFromUrl(urlPath);
		 * } catch (FileNotFoundException e) { // TODO Auto-generated catch
		 * block e.printStackTrace(); } if (imageByte != null) {
		 * BitmapFactory.Options options = new BitmapFactory.Options();
		 * options.inJustDecodeBounds = false; // int be = (int)
		 * (options.outHeight / 50f); // if (be <= 0) { // be = 1; // } //
		 * options.inSampleSize = be;
		 * 
		 * options.inSampleSize = computeSampleSize(options, 50, 50);
		 * 
		 * return BitmapFactory.decodeByteArray(imageByte, 0, imageByte.length,
		 * options); } else { return null; }
		 */
	}

	static int computeSampleSize(BitmapFactory.Options options, int minSideLength,
			int maxNumOfPixels) {
		int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
		int roundedSize;
		if (initialSize <= 8) {
			roundedSize = 1;
			while (roundedSize < initialSize) {
				roundedSize <<= 1;
			}
		} else {
			roundedSize = (initialSize + 7) / 8 * 8;
		}

		return roundedSize;
	}

	private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength,
			int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h
				/ maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));
		if (upperBound < lowerBound) {
			// return the larger before when there is no overlapping zone.
			return lowerBound;
		}

		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	@SuppressWarnings("unused")
	private byte[] getImageFromUrl(String urlPath) throws FileNotFoundException {
		// TODO Auto-generated method stub
		byte[] result = null;
		// 取拍照的byte
		if (urlPath.startsWith("file://")) {
			urlPath = urlPath.substring(7, urlPath.length());

			File file = new File(urlPath);

			FileInputStream fileInputStream = new FileInputStream(file);

			result = new byte[(int) file.length()];

			try {
				fileInputStream.read(result);
			} catch (IOException e) {
				result = null;
				QLog.error("MThumbnailPhoto: " + e.toString());
			} finally {
				try {
					fileInputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			// 取相册的byte
		} else if (urlPath.startsWith("content:/")) {
			ContentResolver resolver = mContext.getContentResolver();
			InputStream inStream = resolver.openInputStream(Uri.parse(urlPath));
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			try {
				byte[] buf = new byte[256];
				int len = 0;
				while ((len = inStream.read(buf)) != -1) {
					arrayOutputStream.write(buf, 0, len);
				}
				arrayOutputStream.flush();
				result = arrayOutputStream.toByteArray();
			} catch (IOException e) {
				result = null;
				QLog.error("MThumbnailPhoto: " + e.toString());
			} finally {
				try {
					inStream.close();
					arrayOutputStream.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return result;
	}
  /**
   * 只有相册在使用
   * @param path
   * @param size
   * @return
   */
	public static Bitmap fitSizeImg(String path, int size) {
		if (path == null || path.length() < 1)
			return null;
		if (path.startsWith("file://")) {
			path = path.substring(7, path.length());
		} else if (path.startsWith("content:/")) {
			path = path.substring(9, path.length());
		}
		File file = new File(path);
		Bitmap resizeBmp = null;
	String filepath=file.getPath();
	//小图
	if(filepath.endsWith("s.jpg")){
		BitmapFactory.Options opts = new BitmapFactory.Options();	
		opts.inSampleSize = size;
		resizeBmp = BitmapFactory.decodeFile(file.getPath(), opts);
	}else{
	//大图
		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inJustDecodeBounds=true;	
		opts.inSampleSize = 0;
	    boolean Rotate=false;
		resizeBmp = BitmapFactory.decodeFile(filepath, opts);
		if(opts.outHeight>opts.outWidth){
		int wid=opts.outWidth/KidApp.SCREEN_WIDTH;
		int hei=opts.outHeight/KidApp.SCREEN_HEIGHT;
		if(wid>hei){
			size=wid;
		}else{
			size=hei;
		}
		}else{
			Rotate=true;
			int wid=opts.outWidth/KidApp.SCREEN_HEIGHT;
			int hei=opts.outHeight/KidApp.SCREEN_WIDTH;
			
			if(wid>hei){
				size=wid;
			}else{
				size=hei;
			}
		}
		resizeBmp=null;		
		opts.inJustDecodeBounds=false;
		opts.inSampleSize = size;
		try{
		resizeBmp = BitmapFactory.decodeFile(filepath, opts);
		}catch(java.lang.OutOfMemoryError err){
			System.gc();
			try{
				resizeBmp = BitmapFactory.decodeFile(filepath, opts);
				}catch(java.lang.OutOfMemoryError err1){
			    
			}
		}
		if(Rotate){
		Matrix matrix = new Matrix();  
		matrix.postRotate(90); /*翻转90度*/  
		int width = resizeBmp.getWidth();  
		int height = resizeBmp.getHeight();  
		resizeBmp = Bitmap.createBitmap(resizeBmp, 0, 0, width, height, matrix, true);}
		}
		return resizeBmp;
	}
	
	public static Bitmap lessBitmap(Bitmap map, int destWith, int destHeight) {
		if (map == null) {
			return null;
		}
		int w = map.getWidth();
		int h = map.getHeight();
		Matrix matrix = new Matrix();
		if (w > h) {
			//matrix.postRotate(90, (float) destWith / 2, (float) destHeight / 2);
			float scaleW = (float) destWith / h;
			float scaleH = (float) destHeight / w;
			if (scaleW > 1 && scaleH > 1) {
				matrix.postScale(1, 1);
			} else {
				if (scaleW > scaleH) {
					matrix.postScale(scaleW, scaleW);
				} else {
					matrix.postScale(scaleH, scaleH);
				}
			}
		} else {
			float scaleW = (float) destWith / w;
			float scaleH = (float) destHeight / h;
			if (scaleW > 1 && scaleH > 1) {
				matrix.postScale(1, 1);
			} else {
				if (scaleW > scaleH) {
					matrix.postScale(scaleW, scaleW);
				} else {
					matrix.postScale(scaleH, scaleH);
				}
			}
		}
		Bitmap newBitmap = Bitmap.createBitmap(map, 0, 0, w, h, matrix, true);
		return newBitmap;
	}

	public static void saveMyBitmap(String bitName, Bitmap bitmap) throws IOException {
		File f = new File(bitName + "s.jpg");
		try {
			f.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		FileOutputStream fOut = null;
		try {
			fOut = new FileOutputStream(f);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fOut);
		try {
			fOut.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		try {
			fOut.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//解析图片的方法
		public static Bitmap lessBitmap(Activity activity,String path){
			Display display = activity.getWindowManager().getDefaultDisplay();
			int width = display.getWidth();
			int height = display.getHeight();
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
			int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
			int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
			if (heightRatio > 1 && widthRatio >1)
			{
			if (heightRatio > widthRatio)
			{
			// Height ratio is larger, scale according to it
			bmpFactoryOptions.inSampleSize = heightRatio;
			}
			else
			{
			// Width ratio is larger, scale according to it
			bmpFactoryOptions.inSampleSize = widthRatio;
			}
			}
			// Decode it for real
			bmpFactoryOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
			return bmp;
		}

		public static Bitmap lessBitmapPath(String path, int wid, int hei) {
			BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
			bmpFactoryOptions.inJustDecodeBounds = true;
			Bitmap bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
			int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)wid);
			int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)hei);
			if (heightRatio > 1 && widthRatio >1)
			{
			if (heightRatio > widthRatio)
			{
			// Height ratio is larger, scale according to it
			bmpFactoryOptions.inSampleSize = heightRatio;
			}
			else
			{
			// Width ratio is larger, scale according to it
			bmpFactoryOptions.inSampleSize = widthRatio;
			}
			}
			// Decode it for real
			bmpFactoryOptions.inJustDecodeBounds = false;
			bmp = BitmapFactory.decodeFile(path, bmpFactoryOptions);
			return bmp;
		}

		
}
